<template>
  <el-dialog
    title="上传文件"
    :close-on-click-modal="false"
    @close="closeHandle"
    :visible.sync="visible"
    append-to-body>

    <el-upload
      :action="url"
      :auto-upload="false"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      :limit="1"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只支持xls,xlsx格式</div>
    </el-upload>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="download">模板下载</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      url: '',
      num: 0,
      successNum: 0,
      fileList: []
    }
  },
  methods: {
    init () {
      this.url = this.$http.BASE_URL + `/event/calendar/upload?token=${this.$cookie.get('token')}`
      this.visible = true
    },
    // 上传之前
    beforeUploadHandle (file) {
      console.log(file.type)
      if (file.type !== 'application/vnd.ms-excel' && file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$message.error('只支持xls,xlsx格式！')
        return false
      }
      this.num++
    },
    submitUpload () {
      this.$children[0].$children[0].submit()
      // this.visible = false
    },
    download () {
      const { export_json_to_excel } = require('../../../excel/Export2Excel')
      const tHeader = ['分类(多个分类用英文逗号隔开)','排序','标题','外链','封面','简介','详细','开始时间（格式为yyyy-MM-dd）','结束时间（格式为yyyy-MM-dd）'] // 对应表格输出的title
      const filterVal = ['categoryTitle', 'sort', 'title', 'link', 'cover', 'introduce', 'content', 'startTime', 'endTime'] // 对应表格输出的数据
      const exceldata = this.formatJson(filterVal, [{'categoryTitle':'金卡', 'sort':'', 'title':'测试日历标题', 'link':'', 'cover':'', 'introduce':'', 'content':'', 'startTime':'2022-9-1', 'endTime':'2022-10-1'}])
      export_json_to_excel([tHeader], [exceldata], '活动日历')// 对应下载文件的名字
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 上传成功
    successHandle (response, file, fileList) {
      this.fileList = []
      this.successNum++
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm('操作成功, 是否继续操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.visible = false
          })
        }
      } else {
        this.$message.error(response.msg)
      }
    },
    // 弹窗关闭时
    closeHandle () {
      this.fileList = []
      this.$emit('refreshDataList')
    }
  }
}
</script>
